/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar.lualib;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.VarArgFunction;

/**
 * Lua 日志输出接口
 */
public class LuaLogger extends TwoArgFunction
{
	private static final Logger logger =
			LogManager.getLogger("com.lucky_byte.pay.Script");

	@Override
	public LuaValue call(LuaValue modname, LuaValue env) {
		LuaValue library = tableOf();
		env.set("logger", library);

		library.set("log", new Log());
		return library;
	}

	/**
	 * 记录日志，这个函数通常不被直接使用，而是通过 lua 扩展函数
	 * logger.debug(), logger.info() ... 等等来调用.
	 */
	class Log extends VarArgFunction
	{
		@Override
		public Varargs invoke(Varargs args) {
			if (!args.isstring(1)) {
				logger.error("Logger 的第一个参数必须为日志级别字符串.");
				return LuaValue.valueOf(-1);
			}
			Level level = Level.toLevel(args.tojstring(1));
			logger.log(level, args.tojstring(2));
			return LuaValue.valueOf(0);
		}
	}

}